function111 [cost, results] = FitnessFunc_CBonly(x, mpc, P_loss0, V_dev0)
%% 阶段1适应度：仅优化 CB 台数（SVG 禁止介入）
% 约束：Q 不倒送；PCC PF ∈ [0.90, 0.93]；电压不越限

%% 参数
pf_lo=0.999; pf_hi=0.93; P_deadband=0.00;
enforce_no_Q_export=true; Q_export_tol=0.02;
limit_local_overcomp=true; cb_keep_ratio_of_Qd=0.05;
alpha1=0.7; alpha2=0.3; vmax_hi=1.05; vmax_lo=0.95;

%% 解码 CB 台数（3/4/5维兼容）
n=numel(x);
if     n>=5, idx=[3,4,5];
elseif n==4, idx=[2,3,4];
elseif n==3, idx=[1,2,3];
else, error('x 维度不对'); end
CB_steps = zeros(3,1);
for i=1:3
    CB_steps(i)=min(mpc.cb(i,3), max(0, round(x(idx(i))*mpc.cb(i,3))));
end

%% 投 CB：严格“整数台数 × 步长”
Qstep_Mvar = mpc.cb(:,2)*mpc.baseMVA;   % 每步 Mvar
m = mpc; Q_cb_applied=zeros(3,1);
for i=1:3
    bi=mpc.cb(i,1); Qd0=mpc.bus(bi,4); stepM=Qstep_Mvar(i);
    req_steps = CB_steps(i);
    % 不过补保留
    Qd_floor = 0;
    if limit_local_overcomp, Qd_floor = cb_keep_ratio_of_Qd*max(Qd0,0); end
    Q_allow = max(Qd0 - Qd_floor, 0);
    allow_steps  = floor(Q_allow/stepM + 1e-9);
    applied_steps= min(req_steps, allow_steps);
    Qcb = applied_steps*stepM;
    Q_cb_applied(i)=Qcb;
    m.bus(bi,4)=Qd0 - Qcb;
end

% 禁 SVG
if isfield(m,'svg') && isfield(m.svg,'gen_idx') && ~isempty(m.svg.gen_idx)
    gidx=m.svg.gen_idx; m.gen(gidx,3)=0; m.gen(gidx,4)=0; m.gen(gidx,5)=0;
end

try
    r = runpf(m); if ~r.success, error('PF 不收敛'); end
catch
    cost=1e6; results=fail_result(); return;
end

%% 指标/约束
[P,Q,pf]=slackPQPF(r); pf_abs=abs(pf);
V=r.bus(:,8);
v_violation = sum(max(0,V - vmax_hi)) + sum(max(0, vmax_lo - V));
penalty = 300*v_violation;
if enforce_no_Q_export && (Q < -Q_export_tol)
    penalty = penalty + 1000*(-Q - Q_export_tol);
end
if abs(P) > P_deadband
    if pf_abs < pf_lo, penalty = penalty + 800*(pf_lo - pf_abs);
    elseif pf_abs > pf_hi && Q >= 0, penalty = penalty + 400*(pf_abs - pf_hi);
    end
end

loss = real(sum(get_losses(r)));
vdev = sum(abs(V - 1.0));
if ~isfinite(P_loss0)||P_loss0<=0, P_loss0=max(loss,1e-6); end
if ~isfinite(V_dev0) ||V_dev0<=0,  V_dev0 =max(vdev,1e-6); end
cost = alpha1*(loss/P_loss0) + alpha2*(vdev/V_dev0) + penalty;

%% 输出
results = struct();
results.bus=r.bus; results.gen=r.gen; results.branch=r.branch;
results.loss=loss; results.v_dev=vdev; results.P_pcc=P; results.Q_pcc=Q; results.pf=pf_abs;
results.CB_steps=CB_steps; results.Q_cb=Q_cb_applied; results.Q_svc=0; results.cost=cost;
end

%% 工具
function R=fail_result(), R=struct('loss',NaN,'v_dev',NaN,'penalty',1e6,'cost',1e6); end
function [P_slack,Q_slack,pf_val]=slackPQPF(res)
sl=(res.gen(:,1)==1); P_slack=sum(res.gen(sl,2)); Q_slack=sum(res.gen(sl,3));
S=hypot(P_slack,Q_slack); if S<1e-9, pf_val=1.0; else, pf_val=P_slack/S; end
end
